import { observable, action, useStrict, computed, asMap, toJS } from 'mobx';
import { Tools,Toast } from 'weaver-mobile';
import BaseStore from './BaseStore';
import * as API_REQ from '../apis/form';
import { CKRichText } from 'weaver-mobile-page';
import base from '../util/base';
import * as Util from '../util/formUtil';
import * as continuationProcessUtil from '../util/continuationProcessUtil';
import { _,GlobalUtil, InvoiceUtil } from '../util/pcPublic';
import * as EmSDK from "../util/emSDK";
import * as authTypes from "../constants/secondAuthType";
import {doFileUpload} from "../util/submit";
import {getFlowHandwrite} from "../util/emSDK";
import {QYSUKeyUtil} from '../util/QYSUkeyUtil';
import loadjs from 'loadjs';
const {ls} = Tools;
const CKRichEditor = CKRichText.CKRichEditor;
const initState = {
    urlParams: {},
    loading: false,
    btnDisabled: true,
    tabKey: "layout",
    commonParam: {},
    invalidParam: {},
    closeNeedPrompt: true,
    invertionInfo: {},
    promptInfos: [],
    conflictFieldMap: observable.map ? observable.map({}): asMap({})

}
// useStrict(true);
export class GlobalStore extends BaseStore{
    urlParams;
    loading;
    @observable richEditorStore = new CKRichEditor.Store();
    @observable btnDisabled;
    @observable tabKey;
    commonParam;       //常用有效参数
    invalidParam;      //剩余无效参数,后期去掉
    closeNeedPrompt;     //离开表单是否提示
    @observable invertionInfo; //流程干预
    @observable promptInfo;    //顶部提示信息
    @observable secLevelInfo = {};//密级信息
    @observable secondAuthInfo = {};    //数据保护验证的信息
    @observable continuationProcessInfo = {};//流程连续处理信息
    @observable conflictFieldMap;

 
    //签字意见回复
    @observable signReplyInfo = {
      reply_status: 'false',
      reply_info: {}
    }; 
    
    @computed get baseParam(){  //基础参数
        let baseParam = {}
        GlobalUtil.baseParamRange.map(k =>{
            baseParam[k] = this.commonParam[k];
        });
        return baseParam;
    }
    @computed get commonApiParam(){     //常用参数，供后端API接口调用
        let apiParam = {}
        GlobalUtil.commonApiParamRange.map(k =>{
            apiParam[k] = this.commonParam[k];
        });
        return apiParam;
    }
    @computed get belongUserStr(){
        const { f_weaver_belongto_userid,f_weaver_belongto_usertype } = this.commonParam;
        return `&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}`;
    }
    @computed get isSourceLayout(){
        const { layoutversion } = this.commonParam;
        return layoutversion === 0 || layoutversion === 1;
    }

    constructor(){
        super();
        this.changeState(initState);
    }

    @action('设置回复标志和被回复人信息')
    setSignReply = (val, data) => {
      this.signReplyInfo.reply_status = val;
      this.signReplyInfo.reply_info = data;
    }
   
    @action('清理回复状态')
    clearReplyInfo = () => {
      this.signReplyInfo.reply_status = false;
      this.signReplyInfo.reply_info = {};
    }

    @action('控制加载条')
    setLoading = (bool=false, msg='Loading...') =>{
        if(this.loading === bool)
            return;
        if(this.loading === false && bool === true){
            Toast.loading(msg, 0);
        }else if(this.loading === true && bool === false){
            Toast.hide();
        }
        this.loading = bool;
    }

    @action('控制按钮置灰')
    setBtnDisabled = (bool=true) =>{
        this.btnDisabled = bool;
    }

    @action("控制发票云参数")
    setInvoiceCloudInfo = (invoiceCloudInfo) => {
        this.invoiceCloudInfo = {...this.invoiceCloudInfo,...invoiceCloudInfo};
    }
    
    @action('控制当前显示tab')
    setTabKey = (key) =>{
      const {mobile_odoc_hidwfbtn} = base.wfLayoutStore.odocInfo;
      this.signReplyInfo.reply_status = false;
      this.signReplyInfo.reply_info = {};
      this.tabKey = key;
      if(key === 'communicate'|| (key == "odoc" && mobile_odoc_hidwfbtn == true ? true : false) ) {
        EmSDK.resetBottomBtn();
        this.commonParam.hasNewCommunication = false;
      } else {
        EmSDK.controlBottomBtn('/req');
      }
      this.clearReplyInfo();
       
    }

    @action('发送接口加载数据')
    loadBaseInfo = (queryParams) =>{
        delete queryParams["preloadkey"];
        delete queryParams["_key"];
        if("returnUrl" in queryParams && !!queryParams.returnUrl){
            Tools.ss.set("__wf__openform__custom__returnurl__", window.decodeURIComponent(queryParams.returnUrl));
        }
        this.urlParams = queryParams;
		
		continuationProcessUtil.showConProcessSwitchTip(queryParams);
        this.setLoading(true);
        const apiLoadStart = new Date().getTime();
        API_REQ.loadBaseInfo({...this.urlParams}).then(data =>{
            window.API_DURATION = new Date().getTime() - apiLoadStart;
            window.SERVER_DURATION = data.durationTime;
            this.doInit(data);
              if(data.conflictFieldInfo) {
              if(typeof data.conflictFieldInfo == 'object') {
                this.changeConflictFieldMap(data.conflictFieldInfo);
              }
            }
             //如果指定了tab,加载完成后跳到对应的tab
             if(queryParams.jumpTab === 'communication') {
                this.setTabKey("communicate");
              }
        });
    }

    @action('加载表单信息')
    doInit = (data) =>{
        const dispatchStart = new Date().getTime();
        this.setLoading(false);
        const params = data.params; //表单所有Params
        //无权限跳转
        if(params.verifyRight === false){
            this.controlVariableMap("verifyRight", false);
            this.controlVariableMap("noRightProps", {isSecNoRight:params.isSecNoRight, isDelete:params.requestIsDelete,isTest:params.isTest});
            return;
        }
        //em的地址，存下来供中转页面使用
        if(params.em_url||params.em_url_open){
            ls.set("wf_em_url",params.em_url)
            ls.set("wf_em_url_open",params.em_url_open)
        }
        //设置有效常用参数
        GlobalUtil.commonParamRange.map(v =>{
            if(v in params){
                this.commonParam[v] = params[v];
                delete params[v]; //删除常用参数
            }
        });
      
        //加载自定义样式文件
        GlobalUtil.loadCustomFiles("css");
        //剩余无效参数(后期逐步去掉)
        this.invalidParam = params; 
        //跨store操作
        const { wfLayoutStore,wfOperateStore,wfRemindStore } = base;
        wfOperateStore.changeSubmitParam(data.submitParams);
        //初始化模板及表单内容
        wfLayoutStore.doInitLayout(data);
        //计量时间
        window.DISPATCH_DURATION = new Date().getTime() - dispatchStart;
        window.REQ_LOAD_DURATION = new Date().getTime() - window.wm_test_body_js_start;
        Util.printDuration(this.commonParam);

        let updateReqInfoFunc = () => {
            //更新请求信息及刷新待办
            const { requestid,iscreate,nodetype,wfmonitor,isurger } = this.commonParam;
            if(iscreate != "1"){
                let updateReqInfoParams  = {...data.submitParams,requestid: requestid, currentnodetype: nodetype, wfmonitor: wfmonitor, isurger: isurger,...GlobalUtil.getUpdateReqInfoFieldValue()};
                API_REQ.updateReqInfo(updateReqInfoParams).then(data=>{});
            }
        }
        //设置顶部提示信息
        this.promptInfos = data.promptInfos;
        //获取流程表单自定义tab
        this.getCustomFormTab()
        //加载顶部快速处理信息
        this.loadContinuationProcessInfo(this.urlParams, updateReqInfoFunc);
        //流程提醒信息
        wfRemindStore.doInit(data.remindInfo);
        //数据保护的验证信息
        this.secondAuthInfo = data.secondAuthInfo;
        //加载右键菜单
        wfOperateStore.loadRightMenu(this.urlParams);
        //加载签字意见输入框信息
        wfOperateStore.loadMarkInfo();
        //密级信息
        this.secLevelInfo = data.secLevelInfo;
        this.loadInterventionInfo();
        //显示CA认证的窗口
        this.showCAAuthDialog(data);
        //获取参数，用于判断是否支持文档签批
        wfOperateStore.getMobileWFOffice()
        //手写签批不保留上次签批的痕迹
        this.setHandWriting();
        //加载水印
        Util.loadWaterMark();
        //加载发票云token
        if(this.commonParam.useInvoiceCloud == true){
            InvoiceUtil.getInvoiceCloudToken();
        }
    }

    @action("打开CA认证的窗口")
    showCAAuthDialog = (data) =>{
        const isCAAuth = this.urlParams.isCAAuth;
        const CAKey = this.urlParams.CAKey;
        if (isCAAuth == "1") {
            const {allStores} = base;
            const {secondAuthStore} = allStores;
            let {secondAuthConfig} = data;
            secondAuthStore.setCallbackFunc(doFileUpload);

            if (!!CAKey) {        //从缓存中先读取之前的数据
                secondAuthStore.readDataFromStorage(CAKey);
            }
            const {authKey, sourcestr,qysSignWay = 2, protectType} = secondAuthConfig;
            secondAuthStore.setCAAuthData({authKey, sourcestr});
            secondAuthStore.setDialogData({qysSignWay});

            if (protectType == authTypes.QYS && qysSignWay == 1) {
                QYSUKeyUtil.showSignWin(secondAuthStore);
            } else if (protectType == authTypes.CA_AUTH) {
                secondAuthStore.controlDialogVisible(authTypes.SECOND_AUTH_DIALOG, true);
            }
        }
    }

    @action('设置关闭是否需要提示')
    setCloseNeedPrompt = (bool=true) =>{
        this.closeNeedPrompt = bool;
    }

    @action("加载流程干预信息")
    loadInterventionInfo = () =>{
        const { wfOperateStore } = base;
        const {intervenorright = 0} = this.commonParam;
        if(intervenorright > 0) {
            API_REQ.getReqInterventionInfo(this.commonApiParam).then(data => {
                this.setInvertionInfo(data);
            base.wfOperateStore.changeSubmitParam({ ...Util.getIntervenorDefaultV(data)});
            })
        }
    }

    @action
    setInvertionInfo = (data = {}) =>{
        this.invertionInfo = {...this.invertionInfo,...data};
    }

    @action("流程干预切换节点")
    getInterventionUser = (selectednodeinfo = {}) =>{
        API_REQ.getInterventionUser({ ...this.commonApiParam, ...selectednodeinfo }).then((data) => {
            const {allStores } = base;
            const { form } = allStores.wfIntervenor;
            const { replacedatas = [] } = data;
            form.updateFields({ Intervenorid: { value: replacedatas }})
            this.setInvertionInfo(data);
            base.wfOperateStore.changeSubmitParam(Util.getIntervenorDefaultV(data));
        });
    }

    @action('重置状态')
    resetAllFormState = () =>{
        this.changeState(initState);
        this.resetVariableMap();
        const { wfLayoutStore,wfOperateStore } = base;
        wfLayoutStore.resetState();
        wfOperateStore.resetState();
    }

    @action("修改表单密级信息")
    setSecLevelInfo = (obj) =>{
        this.secLevelInfo = {...this.secLevelInfo, ...obj};
    }

    setHandWriting=()=>{
      //手写签批不保留上次签批的痕迹
      // this.controlVariableMap("handleWriting_inherit",false);
      //如果上次保存的时候，有手写签批内容，这次打开流程就会获取手写签批内容
      getFlowHandwrite(this.commonParam.requestid);
  }

  @action('加载流程连续处理信息')
    loadContinuationProcessInfo = (queryParams, updateReqInfoFunc) => {
        if(queryParams.isOpenContinuationProcess == '1') {
			let searchConditionParams = {};
            if(localStorage.continuationProcess_searchConditionParams) {
                searchConditionParams = JSON.parse(localStorage.continuationProcess_searchConditionParams)
            }
            API_REQ.getContinnuationProcessInfo({viewScope: "doing", currentRequestId : queryParams.requestid, ...searchConditionParams}).then(data => {
                if(data.isOpenContinuationProcess && data.currentIndex >= 0) {
                    this.continuationProcessInfo = {loaded : true, currentIndex : data.currentIndex, counts : data.count, requestId : queryParams.requestid}
                } else {
                    this.urlParams.isOpenContinuationProcess = '0';
                }
                //更新请求信息及刷新待办
                updateReqInfoFunc();
            })
        } else {
            //更新请求信息及刷新待办
            updateReqInfoFunc();
        }

        //连续处理保存表单刷新流程，直接取上次的连续处理信息显示
        if(queryParams.isOpenContinuationProcess == '1' && queryParams.isRefresh == '1') {
            this.continuationProcessInfo = {
                loaded : true,
                isRefresh : '1',
                currentIndex : queryParams.currentIndex,
                counts : queryParams.counts,
                requestId : queryParams.requestid
            }
        }
    }

    @action('隐藏流程连续处理功能条')
    hideContinuationProcessBar = () => {
        let newContinuationProcessInfo = {...newContinuationProcessInfo, loaded : false};
        this.continuationProcessInfo = newContinuationProcessInfo;
    }

    @action('重新设置流程快速处理信息') 
    resetContinuationProcessInfo = (newContinuationProcessInfo) => {
        this.continuationProcessInfo = {...newContinuationProcessInfo};
    }

    @action('获取流程表单自定义tab')
    getCustomFormTab = () => {
        API_REQ.getFormTab(this.commonApiParam).then((data = {}) => {
            const { customTabs = [] } = data;
            const customFiles = [];
            customTabs.map((tab = {}) => {
                const { filePath = '' } = tab;
                if (filePath.endsWith(".js")) {
                    customFiles.push(filePath);
                }
            });
            if (customTabs.length > 0) {
                const _customTabs =  customTabs.filter(item => item.appendMobileTab == true)
                const _customDrops =  customTabs.filter(item => item.appendMobileDrop == true)
                this.controlVariableMap("customTabs", _customTabs);
                this.controlVariableMap("customDrops", _customDrops);
                const init = () => {
                  if(window.console) console.log("customFiles加载成功！")
                }
                loadjs.isDefined('workflowCustomTab') ? loadjs.ready('workflowCustomTab', init) : loadjs(customFiles, 'workflowCustomTab', init);
            }
        });
    }

    @action('冲突字段值记录')
    changeConflictFieldMap = (obj) => {
      if(typeof obj != 'object') return
        let keys = Object.keys(obj);
        keys.length > 0 && keys.map(key => {
          if(this.conflictFieldMap.has(key)) {
            let temp = {...this.conflictFieldMap.get(key), ...obj[key]};
            this.conflictFieldMap.set(key, temp);
          } else {
            this.conflictFieldMap.set(key, obj[key]);
          }
        })
    }
}